﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

namespace AgileShare.Framework.Library.Helpers
{
	public class SPUserHelper
	{
		/// <summary>
		/// Gets the user friendly name from the logon name
		/// </summary>
		/// <param name="logonName"></param>
		/// <returns></returns>
		public static string GetUserFriendlyName(string logonName)
		{
			string result = null;
			try
			{
				SPSecurity.RunWithElevatedPrivileges(delegate()
				{
                    SPServiceContext serverContext = SPServiceContext.GetContext(SPContext.Current.Site);
					if (serverContext != null)
					{
						UserProfileManager userProfileManager = new UserProfileManager(serverContext);
						if (userProfileManager != null)
						{
							UserProfile userProfile = userProfileManager.GetUserProfile(logonName);
							if (userProfile != null)
							{
								if (userProfile[PropertyConstants.PreferredName] != null)
								{
									result = (string)userProfile[PropertyConstants.PreferredName].Value;
								}
							}
						}
					}
				});
			}
			catch (UserNotFoundException) { }
			return result;
		}

        /// <summary>
        /// Gets the user friendly name from the personal mysite url
        /// </summary>
        /// <param name="mySiteUrl">Shared mysite url</param>
        /// <param name="userUrl">user full public view mysite url</param>
        /// <returns>Friendly name for the User</returns>
        public static string GetUserFriendlyName(string mySiteUrl, bool isMySite)
        {
            string result = null;
            try
            {
                int startPos = mySiteUrl.IndexOf("accountname=") + 12;   //startPos of the username
                int endPos = mySiteUrl.Length - startPos;        // No of chars to retrieve (len of username)
                string userName = mySiteUrl.Substring(startPos, endPos);
                result = GetUserFriendlyName(userName);
            }
            catch
            {
                // Log  - show username is not found using the useraccount
            }
            return result;
        }

        /// <summary>
        /// Gets the Iso2 code from the logon name
        /// </summary>
        /// <param name="logonName"></param>
        /// <returns></returns>
        public static string GetUserIso2Code(string logonName)
        {
            string result = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPServiceContext serverContext = SPServiceContext.GetContext(SPContext.Current.Site);
                    if (serverContext != null)
                    {
                        UserProfileManager userProfileManager = new UserProfileManager(serverContext);
                        if (userProfileManager != null)
                        {
                            UserProfile userProfile = userProfileManager.GetUserProfile(logonName);
                            if (userProfile != null)
                            {
                                /*
                                if (userProfile[PropertyConstants.PreferredName] != null)
                                {
                                    result = (string)userProfile[PropertyConstants.PreferredName].Value;
                                    
                                }
                                */
                                result = "GB";
                            }
                        }
                    }
                });
            }
            catch (UserNotFoundException) { }
            return result;

        }

		/// <summary>
		/// Gets the users work telephone number from the logon name
		/// </summary>
		/// <param name="logonName"></param>
		/// <returns></returns>
		public static string GetUserWorkNumber(string logonName)
		{
			string result = null;
			try
			{
				SPSecurity.RunWithElevatedPrivileges(delegate()
				{
                    SPServiceContext serverContext = SPServiceContext.GetContext(SPContext.Current.Site);
					if (serverContext != null)
					{
						UserProfileManager userProfileManager = new UserProfileManager(serverContext);
						if (userProfileManager != null)
						{
							UserProfile userProfile = userProfileManager.GetUserProfile(logonName);
							if (userProfile != null)
							{
								if (userProfile[PropertyConstants.WorkPhone] != null)
								{
									result = (string)userProfile[PropertyConstants.WorkPhone].Value;
								}
							}
						}
					}
				});
			}
			catch (UserNotFoundException) { }
			return result;
		}

		/// <summary>
		/// Gets the users personal space from the logon name
		/// </summary>
		/// <param name="logonName"></param>
		/// <returns></returns>
		public static string GetUserPersonalSpace(string logonName)
		{
			string result = null;
			try
			{
				SPSecurity.RunWithElevatedPrivileges(delegate()
				{
                    SPServiceContext serverContext = SPServiceContext.GetContext(SPContext.Current.Site);
					if (serverContext != null)
					{
						UserProfileManager userProfileManager = new UserProfileManager(serverContext);
						if (userProfileManager != null)
						{
							UserProfile userProfile = userProfileManager.GetUserProfile(logonName);
							if (userProfile != null && userProfile.PersonalUrl != null)
							{
								result = userProfile.PersonalUrl.AbsoluteUri;
							}
						}
					}
				});
			}
			catch (UserNotFoundException) { }
			return result;
		}

		/// <summary>
		/// Gets the user email address from the logon name
		/// </summary>
		/// <param name="logonName"></param>
		/// <returns></returns>
		public static string GetUserEmail(string logonName)
		{
			string result = null;
			try
			{
				SPSecurity.RunWithElevatedPrivileges(delegate()
				 {
                     SPServiceContext serverContext = SPServiceContext.GetContext(SPContext.Current.Site);
					 if (serverContext != null)
					 {
						 UserProfileManager userProfileManager = new UserProfileManager(serverContext);
						 if (userProfileManager != null)
						 {
							 UserProfile userProfile = userProfileManager.GetUserProfile(logonName);
							 if (userProfile != null)
							 {
								 if (userProfile[PropertyConstants.WorkEmail] != null)
								 {
									 result = (string)userProfile[PropertyConstants.WorkEmail].Value;
								 }
							 }
						 }
					 }
				 });
			}
			catch (UserNotFoundException) { }
			return result;
		}

        public static SPUser GetSPUserObject(SPListItem spListItem, String fieldName)
        {
            SPUser spUser = null;
            try
            {
                if (fieldName != string.Empty)
                {
                    SPFieldUser field = spListItem.Fields[fieldName] as SPFieldUser;
                    if (field != null && spListItem[fieldName] != null)
                    {
                        SPFieldUserValue fieldValue = field.GetFieldValue(spListItem[fieldName].ToString()) as SPFieldUserValue;
                        if (fieldValue != null)
                        {
                            spUser = fieldValue.User;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return spUser;
        }

        public static SPUser GetSPUser(DataRow item, string key)
        {
            SPFieldUser field = item[key] as SPFieldUser;

            if (field != null && item[key] != null)
            {
                SPFieldUserValue fieldValue = field.GetFieldValue(item[key].ToString()) as SPFieldUserValue;
                if (fieldValue != null)
                {
                    return fieldValue.User;
                }
            }
            return null;
        }

        public static SPUser GetSPUser(SPListItem item, string key)
        {
            SPFieldUser field = item.Fields[key] as SPFieldUser;

            if (field != null && item[key] != null)
            {
                SPFieldUserValue fieldValue = field.GetFieldValue(item[key].ToString()) as SPFieldUserValue;
                if (fieldValue != null)
                {
                    return fieldValue.User;
                }
            }
            return null;
        }
	}
}
